<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 15-2-9
 * Time: 上午10:42
 * 手动退款
 * 100：订单号为空
 * 102:非法访问
 * 200：成功
 */
if (!$_SESSION['memberID'] || $_SESSION['memberID']!=7517) {
    Response('非法访问', 102);
}
if ($_POST['action']=='refundManual' && $_POST['order_num'] && $_POST['log_id']) {
    include '/var/www/html/wx/wechat/core/db.lib.php';
    $log_id    = $_POST['log_id'];
    $ordernum  = $_POST['order_num'];
    $db = \LaneWeChat\Core\Db::Connect();
    //TODO::根据交易号获取订单数据
    $sql = "SELECT id,aid,ordernum,refund_status,refund_fee,refund_money as total_fee,trade_no FROM pft_order_refund WHERE id={$log_id} AND refund_status=0 LIMIT 1";
    $stmt = $db->prepare($sql);
    $stmt->execute();
    $refund_data = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($refund_data) {
        $tnum        = $refund_data['refund_num'];
        if ($refund_data['status']==1) {
            write_logs("记录已更新不需要重复更新.订单号[{$ordernum}]log_id[{$log_id}]");
            //如果这个退款已经处理，不往下执行
            Response('ok', 200);
        }
        
        $callBack = json_decode(curl_refund($refund_data['ordernum'],$refund_data['total_fee']+$refund_data['refund_fee'],$refund_data['total_fee']),true);
        if($callBack['code']!='200'){
            Response($callBack['msg'], $callBack['code']);
        }                
        
        
        $sql = "UPDATE pft_order_refund SET refund_status=1,handler_time=now() WHERE id=$log_id LIMIT 1";
        write_logs("sql3:" . $sql);
        $db->exec($sql);

        $sql = "UPDATE pft_alipay_rec SET status=2 WHERE trade_no='{$refund_data['trade_no']}' LIMIT 1";
        if (($ret=$db->exec($sql)) ===false) {
            write_logs('Error:' . $sql);
        }
        AccessLog($db, $_SESSION['memberID'], 1, "退款|订单号[{$ordernum}],记录ID[{$log_id}]|操作账号[{$_SESSION['account']}]");
        Response('ok', 200);
    }
}

function Response($msg, $code)
{
    $json = '{"code":"'.$code.'", "msg":"'.$msg.'"}';
    exit($json);
}

function write_logs($txt){
    $file = '/var/www/html/new/d/module/alipay_refund/wx_log_'.date('Ymd').'.txt';
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

function AccessLog(PDO $db, $mid, $action, $mark){
    $remote_addr = remote_address();// 访问地址
    $ins = <<<SQL
INSERT INTO `pft_access_log` SET `access_time`=now(),`mid`=$mid,
`access_ip`='$remote_addr',`access_action`=$action,`access_note`='$mark'
SQL;
    return $db->exec($ins);
}

function remote_address(){
    if(getenv("HTTP_CLIENT_IP")) return getenv("HTTP_CLIENT_IP");
    if(getenv("HTTP_X_FORWARDED_FOR")) return getenv("HTTP_X_FORWARDED_FOR");
    if(getenv("REMOTE_ADDR")) return getenv("REMOTE_ADDR");
}

function curl_refund($ordernum,$total_money,$refund_money){
    $url = 'http://121.41.120.34/pft/wepay/refund.php';
    define('SECRET_KEY', 'jCox6VfwwKwbxq7v');
    $token = $ordernum.$total_money.$refund_money.SECRET_KEY;
    $param = array(
            'token'=>md5($token),
            'ordernum'=>$ordernum,
            'total_money'=>$total_money,
            'refund_money'=>$refund_money,           
    );
    $param = base64_encode(json_encode($param));
    $ch = curl_init(); 
   	curl_setopt($ch, CURLOPT_POST, 1); 
   	curl_setopt($ch, CURLOPT_HEADER, 0); 
 	curl_setopt($ch, CURLOPT_URL,$url); 
  	curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  	return curl_exec($ch);    
}